package dfbz.com.controller.meeting;

import dfbz.com.controller.BaseServlet;
import dfbz.com.model.ConJoin;
import dfbz.com.model.Conference;
import dfbz.com.service.MeetingService;
import dfbz.com.service.impl.MeetingServiceImp;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;


@WebServlet("/meeting/*")
public class MeetingServlet extends BaseServlet {

    private MeetingService meetingService = new MeetingServiceImp();

    public void meetingList(HttpServletRequest req, HttpServletResponse resp) {

        try {
            req.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //这是已经经过编码后的，才得到的字符串；问题：默认是用什么字符集编码？
        String current = req.getParameter("current");
        String dep = req.getParameter("dep");
        String title = req.getParameter("title");

        if (current == null) {
            current = "1";
        }

//        用URL编码注意空指针异常,有参数传到地址栏前要先编码

        try {
//            System.out.println("meeting servlet 中的参数：");
//            System.out.println(dep);
//            System.out.println(title);
            if (dep != null && title != null && !"".equals(title)) {
                dep = URLEncoder.encode(dep, "UTF-8");
                title = URLEncoder.encode(title, "UTF-8");
                resp.sendRedirect(req.getContextPath() + "/view/meeting?current=" + current + "&dep=" + dep + "&title=" + title);
            } else if (title != null && !"".equals(title)) {
                title = URLEncoder.encode(title, "UTF-8");
                resp.sendRedirect(req.getContextPath() + "/view/meeting?current=" + current + "&title=" + title);

            } else if (!"请选择部门".equals(dep) && dep != null) {
                dep = URLEncoder.encode(dep, "UTF-8");

                resp.sendRedirect(req.getContextPath() + "/view/meeting?current=" + current + "&dep=" + dep);
            } else {
                resp.sendRedirect(req.getContextPath() + "/view/meeting?current=" + current);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void showDetail(HttpServletRequest req, HttpServletResponse resp) {

        String title = req.getParameter("title");
        System.out.println("meetingServlet中：" + title);

        try {
            resp.sendRedirect(req.getContextPath() + "/view/meetingDetail?title=" + title);

        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    public void publishMeeting(HttpServletRequest req, HttpServletResponse resp) {
        //int count = 4;
        try {
            req.setCharacterEncoding("UTF-8");
            String title = req.getParameter("title");
            String dep = req.getParameter("dep");
            String startTime = req.getParameter("startTime");
            String content = req.getParameter("content");
//       存入会议表中
            if (null != title && null != dep) {
                //找到部门的id
                Integer id = meetingService.findDepId(dep);

                Conference conference = new Conference();
                conference.setContent(content);
                conference.setDeptName(dep);
                SimpleDateFormat sf = new SimpleDateFormat("HH:mm");
                Date parse = sf.parse(startTime);
//                System.out.println(parse.toString());
                conference.setStartTime(parse);
                conference.setTitle(title);
                conference.setPublishDate(new Date());
                conference.setStatus(0);
                conference.setDeptId(id);
                //查找会议总数，总数加一

                long total = meetingService.findTotalMeetingCount();
                String s = java.lang.String.valueOf(total);
                int i = Integer.parseInt(s);
                conference.setId(++i);
                System.out.println(conference);
                //将会议存入会议表中
                meetingService.addMeeting(conference);

//                添加con_join表：该部门有多少个人就添加多少个，会议id
//                根据部门id找到所有成员id
                List<Map<String, Object>> ids = meetingService.findAllMemberIds(id);
//                找到con_join总数
                if (ids != null && ids.size() != 0) {
                    Integer conJoinCount = meetingService.findTotalConJoin();
//                会议id
                    Integer conId = conference.getId();
                    for (Map<String, Object> map : ids) {
                        ConJoin conJoin = new ConJoin();
                        conJoin.setCid(conId);
                        conJoin.setStatus(0);
                        conJoin.setId(++conJoinCount);
                        conJoin.setUid(Integer.parseInt(map.get("id").toString()));
//                    这里去加到con_join中
                        meetingService.addConJoin(conJoin);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            resp.sendRedirect("/view/meeting");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void joinMeeting(HttpServletRequest req, HttpServletResponse resp) {
        String cId = req.getParameter("cId");
        String userId = req.getSession().getAttribute("userId").toString();
//        System.out.println("看这里---------"+cId);
//        根据会议id和userID改con_join status 为1，表示已经参加了会议
        meetingService.changeConJoinStatus(cId, userId);

//        然后再跳回meetingDetail
        try {
            resp.sendRedirect(req.getContextPath() + "/view/meetingDetail?meetingId=" + cId);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
